package factiva;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import util.WebDriverFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static factiva.Entry.login;

/**
 * Created by zhongwei on 2016/12/28.
 */
public class LeftTasksMA {
    static List<String> weeks;

    static {
        try {
            weeks = FileUtils.readLines(new File(ClassLoader.getSystemResource("weeks_all.txt").toURI()), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
        List<String> taskList = FileUtils.readLines(new File(ClassLoader.getSystemResource("left_task_ma.txt").toURI()), "UTF-8");
        WebDriver webDriver = WebDriverFactory.getWebDriver(null);
        login(webDriver);
        for (String str : taskList) {
            String[] arr = str.split("\t");
            String fileName = arr[0];
            File output = new File(fileName + ".txt");
            FileWriter fileWriter = new FileWriter(output, true);
            List<String> lines = FileUtils.readLines(output, "UTF-8");
            Set<String> doneWeeks = new HashSet<>();
            for (String line : lines) {
                String[] record = line.split("\t");
                doneWeeks.add(record[0]);
            }
            for (String week : weeks) {
                if (doneWeeks.contains(week)) continue;
                long start = System.currentTimeMillis();
                System.out.println(fileName + " : " + week + " " + new Date().toLocaleString());
                String[] arr1 = week.split("/");
                String[] arr2 = arr1[0].split("-");
                String[] arr3 = arr1[1].split("-");
                String result = "";
                tryClear(webDriver);
                webDriver.findElement(By.id("frd")).sendKeys(arr2[2]);
                webDriver.findElement(By.id("frm")).clear();
                webDriver.findElement(By.id("frm")).sendKeys(arr2[1]);
                webDriver.findElement(By.id("fry")).clear();
                webDriver.findElement(By.id("fry")).sendKeys(arr2[0]);
                webDriver.findElement(By.id("tod")).clear();
                webDriver.findElement(By.id("tod")).sendKeys(arr3[2]);
                webDriver.findElement(By.id("tom")).clear();
                webDriver.findElement(By.id("tom")).sendKeys(arr3[1]);
                webDriver.findElement(By.id("toy")).clear();
                webDriver.findElement(By.id("toy")).sendKeys(arr3[0]);
                webDriver.findElement(By.id("ftx")).clear();
                webDriver.findElement(By.id("ftx")).sendKeys(arr[1]);
                trySearch(webDriver);
                while (true) {
                    try {
                        result = webDriver.findElement(By.className("ctTab")).getText();
                        if (result.contains("道琼斯"))
                            break;
                    } catch (Exception ex) {

                    }
                }
                fileWriter.write(week + "\t" + result + "\n");
                fileWriter.flush();
                tryBack(webDriver);
                long end = System.currentTimeMillis();
                // 限制请求频率，两分钟一次
                long duration = end - start;
                long twoMinutes = 20 * 1000;
                long shift = twoMinutes - duration;
                if (shift > 0) {
                    Thread.currentThread().sleep(shift);
                }
            }
            fileWriter.flush();
            fileWriter.close();
        }
    }

    public static void tryBack(WebDriver webDriver) {
        try {
            webDriver.navigate().back();
        } catch (Exception e) {
            tryBack(webDriver);
        }
    }

    public static void trySearch(WebDriver webDriver) {
        try {
            webDriver.findElement(By.id("btnSBSearch")).click();
        } catch (Exception ex) {
            System.out.println("refreshing...");
            tryRefresh(webDriver);
            System.out.println("refreshed");
            webDriver.findElement(By.className("prettyBtn")).click();
            trySearch(webDriver);
        }
    }

    public static void tryRefresh(WebDriver webDriver) {
        try {
            String url = webDriver.getCurrentUrl();
            webDriver.get(url);
        } catch (Exception e) {
            tryRefresh(webDriver);
        }
    }

    public static void tryClear(WebDriver webDriver) {
        try {
            webDriver.findElement(By.id("frd")).clear();
        } catch (Exception ex) {
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tryClear(webDriver);
        }
    }
}
